package com.superman.supermarket.client.event;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.http.client.URL;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.superman.mvpframe.client.event.LoginEvent;
import com.superman.mvpframe.client.event.ToastEvent;
import com.superman.mvpframe.client.gin.XGinjector;
import com.superman.mvpframe.client.router.INeedLoginPlace;
import com.superman.mvpframe.client.utils.StringUtils;
import com.superman.mvpframe.client.utils.ToastUtils;
import com.superman.supermarket.client.gin.ShopGinjector;

/**
 * 基础事件统一处理类
 * 
 * @author superman
 * @version 2018年7月12日下午5:05:58
 */
public class ShopBaseEventHandler {

	private HandlerRegistration addBaseHandlerRegistration() {
		// toast事件统一处理
		final HandlerRegistration toastHandlerRegistration = XGinjector.INSTANCE.getEventBus().addHandler(ToastEvent.TYPE,
				new ToastEvent.ToastEventHandler() {

					@Override
					public void toast(ToastEvent event) {
						ToastUtils.show(event.getMessage());
					}
				});
		// 登录事件统一处理
		final HandlerRegistration loginHandlerRegistration = XGinjector.INSTANCE.getEventBus().addHandler(LoginEvent.TYPE,
				new LoginEvent.LoginEventHandler() {

					@Override
					public void login(LoginEvent event) {
						ShopBaseEventHandler.this.login();
					}
				});

		// 页面跳转事件处理
		final HandlerRegistration pageJumpHandlerRegistration = XGinjector.INSTANCE.getEventBus().addHandler(PageJumpEvent.TYPE,
				new PageJumpEvent.PageJumpEventHandler() {

					@Override
					public void jump(String url) {
						String localUrl = Window.Location.getHost() + Window.Location.getPath();
						if (url.indexOf(localUrl) > -1) {
							jumpByInnerUrl(url);
						} else {
							jumpByOuterUrl(url);
						}
					}
				});

		return new HandlerRegistration() {

			@Override
			public void removeHandler() {
				toastHandlerRegistration.removeHandler();
				loginHandlerRegistration.removeHandler();
				pageJumpHandlerRegistration.removeHandler();
			}
		};
	}

	/**
	 * 外链跳转
	 * 
	 * @author superman
	 * @version 2018年10月18日 上午10:35:53
	 * @param url
	 */
	private void jumpByOuterUrl(String url) {
		// 当前没有登录.则直接跳转
		if (StringUtils.isEmpty(XGinjector.INSTANCE.getUserModel().getSessionid())) {
			Window.Location.assign(url);
		} else {
			replaceHashWhenIsEmpty();
			Window.Location.assign(url);
		}
	}

	private void replaceHashWhenIsEmpty() {
		if (StringUtils.isEmpty(History.getToken())) {
			// 当前路由hash为空时,默认赋值首页的路由hash
			String token = "home:" + System.currentTimeMillis();
			XGinjector.INSTANCE.getHtml5Historian().replaceState(token, "", "#" + token);
		}
	}

	/**
	 * 外链转内链跳转
	 * 
	 * @author superman
	 * @version 2018年10月12日 下午9:22:16
	 * @param url
	 */
	private void jumpByInnerUrl(String url) {
		// 认为是外链配置的内部具体的页面
		if (url.indexOf("#") > -1) {
			String[] surl = url.split("#");
			String purl = surl[0];
			String turl = surl[1];
			// 获取当前的place
			Place targetPlace = ShopGinjector.INSTANCE.getMyHistoryMapper().getPlace(turl);
			if (targetPlace == null) {
				Window.Location.assign(url);
			} else {
				// 判断是否需要登录
				boolean neeedLogin = false;
				if (targetPlace instanceof INeedLoginPlace) {
					neeedLogin = StringUtils.isEmpty(XGinjector.INSTANCE.getUserModel().getSessionid());
				}
				if (neeedLogin) {
					login();
				} else {
					Map<String, Object> contextData = new HashMap<String, Object>();
					if (purl.indexOf("?") > -1) {
						// 包含?号,说明有url参数
						purl = purl.substring(purl.indexOf("?") + 1);

						// 包含&号,说明有多个
						if (purl.indexOf("&") > -1) {
							String[] sps = purl.split("&");
							for (int i = 0; i < sps.length; i++) {
								String[] ppurl = sps[i].split("=");
								contextData.put(ppurl[0], ppurl[1]);
							}
						} else {
							String[] ppurl = purl.split("=");
							contextData.put(ppurl[0], ppurl[1]);
						}
					}

					if (contextData.isEmpty()) {
						XGinjector.INSTANCE.getMyPlaceController().push(targetPlace);
					} else {
						XGinjector.INSTANCE.getMyPlaceController().push(targetPlace, contextData);
					}
				}
			}

		} else {
			// 没有指定具体的place. 则加载首页
			XGinjector.INSTANCE.getMyPlaceController().push(ShopGinjector.INSTANCE.getMyPlaceFactory().getHomePlace());
		}

	}

	/**
	 * 绑定处理器
	 * 
	 * @author superman
	 * @version 2018年7月12日 下午5:06:00
	 */
	public void bind() {
		addBaseHandlerRegistration();
	}

	private void login() {
		replaceHashWhenIsEmpty();
		final String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + getWXAppId() + "&redirect_uri="
				+ URL.encodeQueryString(Window.Location.getHref())
				+ "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		Window.Location.assign(url);
	}

	private native String getWXAppId()/*-{
		return $wnd.WX_APPID;
	}-*/;

}
